//
//  UIAlertViewCustom.m
//  警告框
//
//  Created by mac on 16/5/9.
//  Copyright © 2016年 天津提嗯科技有限公司. All rights reserved.
//

#import "UIAlertViewCustom.h"
#import "UIViewAdditions.h"

#define UIColorLineColor UIColorFromRGB(0Xe5e5e5)
#define UIColorTextDarkColor UIColorFromRGB(0X242829)

#define PaddingTopTitle 20
#define PaddingTopMessage 57
#define PaddingButtonTop 15

#define ButtonHeight 44

const UIWindowLevel UIWindowLevelSIAlertBackground = 1985.0; // below the alert window
static AlertBackgroundWindow *alertBackgroundWindow;

@interface AlertBackgroundWindow ()
@property (strong, nonatomic) NSMutableArray *alertViews;

@end

@implementation AlertBackgroundWindow

- (id)initView
{
    CGRect frame = [[UIScreen mainScreen] bounds];
    self = [super initWithFrame:frame];
    if (self) {
        self.alertViews = [[NSMutableArray alloc] initWithCapacity:1];
        self.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        self.opaque = NO;
        self.windowLevel = UIWindowLevelSIAlertBackground;
        self.backgroundColor = UIColorFromRGBF(0x585d66, 0.3);
    }
    return self;
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
    [super touchesEnded:touches withEvent:event];
    UITouch *touch = [touches anyObject];
    CGPoint point  = [touch locationInView:self];
    UIAlertViewCustom *alertView = (UIAlertViewCustom *)self.subviews.firstObject;
    bool inAlertView = CGRectContainsPoint(alertView.frame, point);
    if (!inAlertView) {
        if (!alertView.disabled) {
            [alertView dismiss];
            return;
        }
    }
    bool inClose = CGRectContainsPoint(alertView.closeButton.screenFrame, point);
    if (inClose && !alertView.closeButton.hidden) {
        [alertView dismiss];
    }
    [self convertPoint:point toView:alertView];
}

@end

@interface UIAlertViewCustom ()
@property (weak, nonatomic) UILabel *titleLab,*messageLab;
@property (weak, nonatomic) UIView *line1;
@property (nonatomic, weak) UIView *line2;
@property (strong, nonatomic) UIFont *titleFont,*messageFont,*buttonFont;
@property (nonatomic) CGFloat height;
@property (strong, nonatomic) UIImageView *closeBtn;
@property (strong, nonatomic) NSMutableArray<UIButton *> *buttonArray;
@property (nonatomic, weak) UIView *contentView;
@end

@implementation UIAlertViewCustom

- (instancetype)initWithTitle:(NSString *)title
                      message:(NSString *)message{
    CGRect frame = CGRectMake(0, 0, rateWidth(300), 120);
    self = [self initWithFrame:frame];
    if (self) {
        _titleLab.text = title;
        self.messageLab.text = message;
        self.layer.cornerRadius = 0;
    }
    return self;
}

- (instancetype)initWithTitle:(NSString *)title contentView:(UIView *)contentView {
    CGRect frame = CGRectMake(0, 0, rateWidth(300), 120);
    self = [self initWithFrame:frame];
    if (self) {
        _titleLab.text = title;
        [self addContentView:contentView];
    }
    return self;
}

- (void)addButtonWithTitle:(NSString *)title state:(UIAlertViewCustomState)state action:(MYAction)action {
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    if (state == UIAlertViewCustomStateOK) {
        [btn setBackgroundImage:UIImageWithColor(UIColorWithRGB(246, 55, 127)) forState:UIControlStateNormal];
        [btn setTitleColor:UIColorWhite forState:UIControlStateNormal];
        btn.titleLabel.font = UIFontSystem(17);
    }
    btn.layer.cornerRadius = 7;
    btn.layer.masksToBounds = YES;
    [btn setTitle:title forState:UIControlStateNormal];
    [self addSubview:btn];
    [self.buttonArray addObject:btn];
    btn.tag = self.buttonArray.count;
    [btn addActionHandler:^(NSInteger tag) {
        [self dismiss];
        action();
    }];
}

- (void)addContentView:(UIView *)contentView {
    _contentView = contentView;
    [self addSubview:contentView];
}

- (id)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self initStatus];
    }
    return self;
}

- (void)initStatus {
    self.backgroundColor = UIColorWhite;
    self.layer.cornerRadius = 10;
    self.layer.masksToBounds = YES;
    self.clipsToBounds = YES;
    _titleFont = [UIFont systemFontOfSize:17];
    _messageFont =[UIFont systemFontOfSize:14];
    _buttonFont = [UIFont systemFontOfSize:16];
    
    UILabel *titleLab = [[UILabel alloc] initWithFrame:CGRectZero];
    titleLab.textAlignment = NSTextAlignmentCenter;
    titleLab.textColor = UIColorWithRGB(246, 85, 146);

    UILabel *messageLab = [UILabel labelWithText:@"" textColor:UIColorBlack fontSize:14];
    messageLab.textAlignment = NSTextAlignmentCenter;
    messageLab.numberOfLines = 0;
    [self addSubview:messageLab];
    
    UIImageView *closeBtn = [[UIImageView alloc] initWithFrame:CGRectZero];
    closeBtn.userInteractionEnabled = YES;
    [closeBtn addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismiss)]];
    [self addSubview:closeBtn];
    
    [self addSubview:titleLab];
    self.titleLab = titleLab;
    self.messageLab = messageLab;
//    _imgViewBtn = imgViewBtn;
//    _closeBtn = closeBtn;
    self.buttonArray = [NSMutableArray arrayWithCapacity:1];
}

- (void)layoutSubviews{
    _height = 0;
    if (_titleLab.text) {
        _titleLab.frame = CGRectMake(0, 20, self.bounds.size.width, 15);
    }
    if (_messageLab.text) {
        _messageLab.frame = CGRectMake(0, _titleLab.bottom+20, [_messageLab.text getSizeWithMaxSize:CGSizeMake(self.width-20, CGFLOAT_MAX) attributes:@{NSFontAttributeName: _messageFont}].width, [_messageLab.text getSizeWithMaxSize:CGSizeMake(self.width-20, CGFLOAT_MAX) attributes:@{NSFontAttributeName: _messageFont}].height);
        _messageLab.centerX = self.centerX;
        _height = _messageLab.bottom + 20;
    }
    if (_contentView) {
        _contentView.frame = CGRectMake(0, _titleLab.bottom+30, self.width, _contentView.height);
        _height = _contentView.bottom+1;
    }
    if (self.buttonArray.count == 1) {
        UIButton *btn = (UIButton *)[self viewWithTag:self.buttonArray.count];
        btn.frame = CGRectMake(rateWidth(30), _contentView.bottom, self.width-rateWidth(60), 44);
        _height = btn.bottom+24;
    } else if (self.buttonArray.count == 2) {
        UIButton *btn1 = (UIButton *)[self viewWithTag:1];
        btn1.frame = CGRectMake(0, _line1.bottom, self.width*0.5, 44);
        UIButton *btn2 = (UIButton *)[self viewWithTag:2];
        btn2.frame = CGRectMake(btn1.right+1, _line1.bottom, self.width*0.5, 44);
        _height = btn2.bottom;
        _line2.frame = CGRectMake(btn1.right, _line1.bottom, 1, 44);
    }
    
    _closeBtn.frame = CGRectMake(240, 0, 30, 30);
    CGRect selfFrame = self.frame;
    selfFrame.size.height = _height;
    self.frame = selfFrame;
    self.center = alertBackgroundWindow.center;
}

- (void)show {
    [self showWithCloseButton:NO];
}
+ (void)showBackground{
    if (!alertBackgroundWindow) {
        alertBackgroundWindow = [[AlertBackgroundWindow alloc] initView];
        [alertBackgroundWindow makeKeyAndVisible];
        alertBackgroundWindow.alpha = 0;
        [UIView animateWithDuration:0.3
                         animations:^{
                             alertBackgroundWindow.alpha = 1;
                         }];
    }
}
- (void)showWithCloseButton:(BOOL)show{
    
    [UIAlertViewCustom showBackground];
    if (alertBackgroundWindow.alertViews.count < 1) {
        self.closeButton.hidden = !show;
        [alertBackgroundWindow.alertViews addObject:self];
        [alertBackgroundWindow addSubview:self];
    }else{
        BOOL added = NO;
        for (UIAlertViewCustom *alert in alertBackgroundWindow.alertViews) {
            added = (alert.tag == 1112);
            if (added) {
                break;
            }
        }
        if (!added) {
            [alertBackgroundWindow.alertViews addObject:self];
        }
    }
}

- (void)dismiss{
//    if (alertBackgroundWindow.alertViews.count == 1) {
//        [alertBackgroundWindow.alertViews removeLastObject];
//        [self removeFromSuperview];
//        alertBackgroundWindow.alpha = 0;
//        alertBackgroundWindow = nil;
//    }else{
//        [self removeFromSuperview];
//        [alertBackgroundWindow.alertViews removeObject:self];
//        [alertBackgroundWindow addSubview:alertBackgroundWindow.alertViews.firstObject];
//        alertBackgroundWindow.alpha = 0;
//        alertBackgroundWindow = nil;
//    }

}

@end
